package com.sc.es.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sc
 * Created on  2018/2/7
 * 基于角色的登录入口
 */
public class LoginUrlEntryPoint extends LoginUrlAuthenticationEntryPoint{
    private final Map<String,String> authMap;
    private PathMatcher pathMatcher =new AntPathMatcher();
    public LoginUrlEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
        this.authMap = new HashMap<>();
        authMap.put("/user/**","/user/login");
        authMap.put("/admin/**","/admin/login");
    }

    @Override
    protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        String uri = request.getRequestURI().replace(request.getContextPath(), "");
        for (Map.Entry<String, String> entry : authMap.entrySet()) {
            if(this.pathMatcher.match(entry.getKey(),uri)){
                return entry.getValue();
            }
        }
        return super.determineUrlToUseForThisRequest(request,response,exception);
    }

}
